﻿using System;
using System.Linq;
using System.Windows;
using GTasks;
using GTasksPlus.Code;
using GTasksPlus.Model;
using Microsoft.Phone.Shell;

namespace GTasksPlus.Views
{
    public partial class ManipulateList
    {
        private static string _id = String.Empty;

        public ManipulateList()
        {
            if (IsLoggedIn())
                InitializeComponent();
            else
                NavigationService.Navigate(new Uri("/Login.xaml", UriKind.RelativeOrAbsolute));
        }

        private void GetResponse(bool obj)
        {
            App.MainViewModel.LoadData();
            performanceProgressBar.Visibility = Visibility.Collapsed;
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ApplicationTitle.Text = GTasksSettings.ApplicationTitle;
            if (NavigationContext.QueryString.ContainsKey("Id"))
            {
                AddUpdateButton();
                _id = NavigationContext.QueryString["Id"];
                if (!_id.Equals("new"))
                {
                    var s = from p in App.MainViewModel.Tasks
                            where p.id == _id
                            select p;
                    TaskItem.Text = s.Single().title;
                    AddDeleteButton();
                }
                else
                {
                    PageTitle.Text = PageTitle.Text.Replace("edit", "add");
                }
            }
        }

        private void AddDeleteButton()
        {
            var deleteButton = new ApplicationBarIconButton { Text = "Delete", IconUri = new Uri("/Images/delete.png", UriKind.Relative) };
            deleteButton.Click += DeleteClick;
            if (ApplicationBar.Buttons.IndexOf(deleteButton) < 0)
                ApplicationBar.Buttons.Add(deleteButton);
        }

        private void AddUpdateButton()
        {
            var saveButton = new ApplicationBarIconButton { Text = "Save", IconUri = new Uri("/Images/save.png", UriKind.Relative) };
            saveButton.Click += SaveClick;
            if (ApplicationBar.Buttons.IndexOf(saveButton) < 0)
                ApplicationBar.Buttons.Add(saveButton);
        }

        #region Event Handlers

        private void DeleteClick(object sender, EventArgs eventArgs)
        {
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
            performanceProgressBar.Visibility = Visibility.Visible;
            var s = from p in App.MainViewModel.Tasks
                    where p.id == _id
                    select p;
            s.Single().Delete(GetResponse);
        }

        private void SaveClick(object sender, EventArgs eventArgs)
        {
            if (!string.IsNullOrEmpty(TaskItem.Text.Trim()))
            {
                ((ApplicationBarIconButton) ApplicationBar.Buttons[0]).IsEnabled = false;
                performanceProgressBar.Visibility = Visibility.Visible;
                if (!_id.Equals("new"))
                {
                    var s = from p in App.MainViewModel.Tasks
                            where p.id == _id
                            select p;
                    var taskList = s.SingleOrDefault();
                    if (taskList != null)
                    {
                        taskList.title = TaskItem.Text.Trim();
                        taskList.Update(GetResponse);
                    }
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                }
                else
                {
                    TaskListHelper.AddTaskList(
                        new TaskListItem(TaskItem.Text.Trim(), String.Empty, String.Empty, String.Empty), GetResponse);
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            while (NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
            e.Cancel = true;
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        #endregion
    }
}